package com.greenet.companytemplate.manager.web;

import com.greenet.companytemplate.manager.entity.FileBean;
import com.greenet.companytemplate.manager.entity.Menu;
import com.greenet.companytemplate.manager.entity.TMenu;
import com.greenet.companytemplate.manager.service.FileService;
import com.greenet.companytemplate.manager.service.SecondMenuService;
import com.greenet.companytemplate.manager.service.ThirdMenuService;
import org.apache.tools.zip.ZipFile;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.util.Date;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;


/**
 * Created by Administrator on 2016/4/26.
 */
@Controller
public class UploadController {
    protected Logger logger= LoggerFactory.getLogger(getClass());
    @Autowired
    private SecondMenuService secondMenuService;
    @Autowired
    private ThirdMenuService thirdMenuService;
    @Autowired
    private FileService fileService;
    /**
     * 使用GBK编码可以避免压缩中文文件名乱码
     */
    private static final String CHINESE_CHARSET = "GBK";
    /**
     * 文件读取缓冲区大小
     */
    private static final int CACHE_SIZE = 1024;
    /**
     * 上传菜单连接的附件 解释：菜单中有热连接需要点击
     * @param request
     * @param multipartHttpServletRequest
     * @param parentId
     * @param secondId
     * @param thirdId
     * @return
     * @throws IOException
     */
    @RequestMapping("/upload/file")
    @ResponseBody
    public String upload(HttpServletRequest request,MultipartHttpServletRequest multipartHttpServletRequest,
                         @RequestParam("parentId") int parentId,
                         @RequestParam("secondId") int secondId,
                         @RequestParam(value = "thirdId",required = false) String thirdId
                         ) throws Exception {
        //将用户上传的文件，生成到webapp/resources下的upload文件夹下
//        System.out.println(mainfile.getOriginalFilename()+"主文件");
        String path=request.getSession().getServletContext().getRealPath("/resources/upload");
        MultipartFile file = null;
        Iterator<String> itr =  multipartHttpServletRequest.getFileNames();
        while(itr.hasNext()){
            file = multipartHttpServletRequest.getFile(itr.next());
            String fileName=file.getOriginalFilename();
            logger.info(file.getOriginalFilename() +" uploaded! ");

            if(thirdId!=null && !"".equals(thirdId)){

                File f = new File(path + "/" + parentId + "/" + secondId+"/"+thirdId);
                if (!f.exists()) {
                    f.mkdirs();
                }
                File ff = new File(path + "/" + parentId + "/" + secondId + "/" + thirdId + "/" + fileName);
                if (ff.exists()) {
                    ff.delete();
                } else {
                    ff.createNewFile();
                }
                file.transferTo(ff);
                if(fileName.toLowerCase().contains(".zip") || fileName.toLowerCase().contains(".rar")){
                    this.unZip(path + "/" + parentId + "/" + secondId + "/" + thirdId + "/" + fileName,path + "/" + parentId + "/" + secondId+"/"+thirdId+"/");
                }
            }else {
                File f = new File(path + "/" + parentId + "/" + secondId);
                if (!f.exists()) {
                    f.mkdirs();
                }
                File ff = new File(path + "/" + parentId + "/" + secondId + "/" + fileName);
                if (ff.exists()) {
                    ff.delete();
                } else {
                    ff.createNewFile();
                }
                file.transferTo(ff);
                if(fileName.toLowerCase().contains(".zip") || fileName.toLowerCase().contains(".rar")){
                    this.unZip(path + "/" + parentId + "/" + secondId  + "/" + fileName, path + "/" + parentId + "/" + secondId+"/");
                }
            }
        }
        return "another";
    }

    /**
     * 上传菜单连接的文件（此称主文件）
     * @param request
     * @param multipartHttpServletRequest
     * @param parentId
     * @param secondId
     * @param thirdId
     * @return
     * @throws IOException
     */
    @RequestMapping("/upload/main")
    @ResponseBody
    public String uploadmain(HttpServletRequest request,MultipartHttpServletRequest multipartHttpServletRequest,
                         @RequestParam("parentId") int parentId,
                         @RequestParam("secondId") int secondId,
                         @RequestParam(value = "thirdId",required = false) String thirdId
    ) throws IOException {
        //将用户上传的文件，生成到webapp/resources下的upload文件夹下
//        System.out.println(mainfile.getOriginalFilename()+"主文件");
        String path=request.getSession().getServletContext().getRealPath("/resources/upload");
        MultipartFile file = null;
        Iterator<String> itr =  multipartHttpServletRequest.getFileNames();
        Date date=new Date();
        while(itr.hasNext()){

            file = multipartHttpServletRequest.getFile(itr.next());
            String fileName=file.getOriginalFilename();

            logger.info(file.getOriginalFilename() +" uploaded! ");
            if(thirdId!=null && !"".equals(thirdId)){
                File f = new File(path + "/" + parentId + "/" + secondId+"/"+thirdId);
                if (!f.exists()) {
                    f.mkdirs();
                }
                File ff = new File(path + "/" + parentId + "/" + secondId + "/"+thirdId+"/" + fileName);
                if (ff.exists()) {
                    ff.delete();
                } else {
                    ff.createNewFile();
                }
                file.transferTo(ff);
                String endPath = "/resources/upload/" + parentId + "/" + secondId + "/"+thirdId+"/" + fileName;
                TMenu tMenu=new TMenu();
                tMenu.setId(thirdId);
                tMenu.setUrl(endPath);
                thirdMenuService.updateUrl(tMenu);

                FileBean fileBean=new FileBean();
                fileBean.setName(fileName);
                fileBean.setDate(date);
                fileBean.setUrl(endPath);
                fileBean.setPath(parentId + "/" + secondId + "/"+thirdId);
                fileService.save(fileBean);
            }else {
                File f = new File(path + "/" + parentId + "/" + secondId);
                if (!f.exists()) {
                    f.mkdirs();
                }
                File ff = new File(path + "/" + parentId + "/" + secondId + "/" + fileName);
                if (ff.exists()) {
                    ff.delete();
                } else {
                    ff.createNewFile();
                }
                file.transferTo(ff);
                String endPath = "/resources/upload/" + parentId + "/" + secondId + "/" + fileName;
                Menu menu = new Menu();
                menu.setId(String.valueOf(secondId));
                menu.setUrl(endPath);
                secondMenuService.updateUrl(menu);
                FileBean fileBean=new FileBean();
                fileBean.setName(fileName);
                fileBean.setDate(date);
                fileBean.setUrl(endPath);
                fileBean.setPath(parentId + "/" + secondId);
                fileService.save(fileBean);
            }
        }
        return "main";
    }


    /**
     * 跳转到上传附件的页面
     * @param parentId
     * @param secondId
     * @param filename
     * @param thirdId
     * @param model
     * @return
     */
    @RequestMapping("/upload/another")
    public String uploadanother(@RequestParam("parentId") int parentId,
                         @RequestParam("secondId") int secondId,
                         @RequestParam("filename") String filename,
                         @RequestParam(value = "thirdId",required = false) String thirdId,
                                Model model
    ) {
        model.addAttribute("parentId",parentId);
        model.addAttribute("secondId",secondId);
        model.addAttribute("thirdId",thirdId);
        model.addAttribute("filename",filename);
        return "uploadanother";
    }


    /**
     * <p>
     * 解压压缩包
     * </p>
     *
     * @param zipFilePath 压缩文件路径
     * @param destDir 压缩包释放目录
     * @throws Exception
     */
    public void unZip(String zipFilePath, String destDir) throws Exception {
        ZipFile zipFile = new ZipFile(zipFilePath, CHINESE_CHARSET);
        Enumeration<?> emu = zipFile.getEntries();
        BufferedInputStream bis;
        FileOutputStream fos;
        BufferedOutputStream bos;
        File file, parentFile;
        ZipEntry entry;
        byte[] cache = new byte[CACHE_SIZE];
        while (emu.hasMoreElements()) {
            entry = (ZipEntry) emu.nextElement();
            if (entry.isDirectory()) {
                new File(destDir + entry.getName()).mkdirs();
                continue;
            }
            bis = new BufferedInputStream(zipFile.getInputStream((org.apache.tools.zip.ZipEntry)entry));
            file = new File(destDir + entry.getName());
            parentFile = file.getParentFile();
            if (parentFile != null && (!parentFile.exists())) {
                parentFile.mkdirs();
            }
            fos = new FileOutputStream(file);
            bos = new BufferedOutputStream(fos, CACHE_SIZE);
            int nRead = 0;
            while ((nRead = bis.read(cache, 0, CACHE_SIZE)) != -1) {
                fos.write(cache, 0, nRead);
            }
            bos.flush();
            bos.close();
            fos.close();
            bis.close();
        }
        zipFile.close();
    }



}
